package controllers;

import is.ru.honn.rupin.domain.Pin;
import is.ru.honn.rupin.service.BoardNotFoundException;
import is.ru.honn.rupin.service.PinService;
import play.data.Form;
import play.mvc.Result;
import views.html.pins.form;

/**
 * @author Einar Sigurðsson
 * @version 0.9, 11/19/12
 */
public class PinController extends RuPinController{
    /**
     * A variable containing the form needed to create new pins
     */
    final static Form<Pin> pinForm = form(Pin.class);

    /**
     * Routes from pins/create/:boardname
     *
     * @param boardname the Board on which to create a pin
     * @return an empty form
     */
    public static Result pinForm(String boardname){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        return ok(form.render(pinForm, boardname));
    }

    /**
     * Adds a pin to the database from the form given in pinForm()
     * @param boardname name of the board on which to create a pin
     * @return The page of the board
     */
    public static Result addPin(String boardname){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        Form<Pin> filledForm = pinForm.bindFromRequest();

        if (filledForm.hasErrors()){
            return badRequest(form.render(filledForm, boardname));
        }
        else
        {
            Pin created = null;
            try{
                created = pinService.createPin(session().get("username"), boardname, filledForm.get().getLink(), filledForm.get().getDescription(), filledForm.get().getImage());
            } catch (BoardNotFoundException e) {
                return status(1234, "The Board wasn't found.");
            }
            System.out.println("created pin: " + created);
            return redirect(routes.BoardController.getBoard(session().get("username"), boardname));
        }
    }
}